package com.yunqiao.common.validator;


import com.yunqiao.common.exception.CustomApiException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2017-03-15 10:50
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws CustomApiException  校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
        throws CustomApiException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getPropertyPath())
                    .append(constraint.getMessage())
                    .append(" ");
            }
            throw new CustomApiException(msg.toString());
        }
    }



    /**
     * 这个是备用方法, 测试上面的方法不好用,就用这个.区别:上面的是拼接处了所有异常,下面则是取第一条
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws CustomApiException  校验不通过，则报RRException异常
     */
    public static void validateBodyEntity(Object object, Class<?>... groups)throws CustomApiException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            //取set集合的第一个元素
            ConstraintViolation<Object> violation = constraintViolations.iterator().next();
            String errorMsg = violation.getPropertyPath() + violation.getMessage();
            throw new CustomApiException(errorMsg);
        }
    }

}
